package com.ylb.rent.service.impl;

import java.util.Collection;
import java.util.List;

import afu.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.ylb.rent.config.PageConfig;
import com.ylb.rent.dao.*;
import com.ylb.rent.entity.*;
import com.ylb.rent.entity.vo.ApartmentDetailVo;
import com.ylb.rent.entity.vo.ApartmentSchoolVo;
import com.ylb.rent.entity.vo.RoomVo;
import com.ylb.rent.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

/**
 * 公寓Service业务层处理
 * 
 * @author ylb
 * @date 2023-06-29
 */
@Service
@Slf4j
public class ApartmentServiceImpl implements IApartmentService
{
    @Autowired
    private ApartmentMapper apartmentMapper;

    @Autowired
    private IApartmentStuffService apartmentStuffService;

    @Autowired
    private ApartmentStuffMapper apartmentStuffMapper;

    @Autowired
    private ApartmentSecurityMapper apartmentSecurityMapper;

    @Autowired
    private ApartmentForbidMapper apartmentForbidMapper;


    @Autowired
    private ApartmentFeetypeMapper apartmentFeetypeMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private ApartmentImageMapper apartmentImageMapper;

    @Autowired
    private IStuffService stuffServiceImpl;

    @Autowired
    private IForbidService forbidService;

    @Autowired
    private ISecurityService securityService;

    @Autowired
    private IFeetypeService feetypeService;

    @Autowired
    private SchoolApartmentDistMapper schoolApartmentDistMapper;

    @Autowired
    private ISchoolService schoolService;

    @Autowired
    CancelMapper cancelMapper;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private ApartmentCountryCityMapper apartmentCountryCityMapper;

    @Autowired
    private CountryMapper countryMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    IFileService fileService;

    @Autowired
    ICityService cityService;

    @Override
    public List<ApartmentDetailVo> selectVoListByCityId(long cId) {

//        查到该城市下的公寓
        QueryWrapper<ApartmentCountryCity> apartmentCountryCityQueryWrapper = new QueryWrapper<>();
        apartmentCountryCityQueryWrapper.eq("city_id",cId);

        List<ApartmentCountryCity> apartmentCountryCities = apartmentCountryCityMapper.selectList(apartmentCountryCityQueryWrapper);
//        查到公寓id集合
        List<Long> apartmentIdList = apartmentCountryCities.stream().map(ApartmentCountryCity::getApartmentId).collect(Collectors.toList());
//        根据id查公寓vo
        return apartmentIdList.stream().map(this::selectApartmentVoById).collect(Collectors.toList());

    }

    /**
     * 查询公寓
     * 
     * @param id 公寓主键
     * @return 公寓
     */
    @Override
    public Apartment selectApartmentById(Long id)
    {

        return apartmentMapper.selectApartmentById(id);
    }

    @Override
    public ApartmentDetailVo selectApartmentVoById(Long id) {
//        公寓基本信息
        Apartment apartment = this.selectApartmentById(id);
        if(ObjectUtil.isNull(apartment)){
            return null;
        }
//        初始化公寓基本信息
        ApartmentDetailVo.ApartmentDetailVoBuilder builder = ApartmentDetailVo.builder()
                .id(apartment.getId())
                .apartmentName(apartment.getApartmentName())
                .address(apartment.getAddress())
                .description(apartment.getDescription())
                .isDelete(apartment.getIsDelete());


        Long aId = apartment.getId();
//        公寓设施
        List<Stuff> stuffs = stuffServiceImpl.selectListByApartmentId(aId);
        builder.stuffList(stuffs);
//        公寓禁止事项
        List<Forbid> forbids = forbidService.selectListByApartmentId(aId);
        builder.forbidList(forbids);
//        公寓安全保障
        List<Security> securities = securityService.selectListByApartmentId(aId);
        builder.securityList(securities);
//        公寓费用
        List<Feetype> feetypes = feetypeService.selectListByApartmentId(aId);
        builder.feetypeList(feetypes);
//        公寓房间
        List<RoomVo> rooms = roomService.selectVoListByApartmentId(aId);
        builder.roomList(rooms);
//        公寓学校
        List<ApartmentSchoolVo> apartmentSchoolVos = schoolService.selectVoListByApartmentId(aId);
        builder.schoolList(apartmentSchoolVos);
//        取消策略
        Cancel cancel = cancelMapper.selectCancelById(apartment.getCancelId());
        builder.cancel(cancel);

//        查询图片
        List<File> files = fileService.selectListByApartmentId(aId);
        List<String> imageList = files.stream().map(File::getFilename).collect(Collectors.toList());
        builder.imageList(imageList);
//        公寓-国家-城市
        List<City> cities = cityService.selectListByApartmentId(aId);
        builder.cityList(cities);

        return builder.build();
    }

    /**
     * 查询公寓列表
     * 
     * @param apartment 公寓
     * @return 公寓
     */
    @Override
    public List<Apartment> selectApartmentList(Apartment apartment)
    {
        return apartmentMapper.selectApartmentList(apartment);
    }

    /**
     * 新增公寓 ,可以继续优化，变成批量插入的方式，懒得写
     * 
     * @param apartmentVo 公寓
     * @return 结果
     */
    @Transactional
    @Override
    public int insertApartment(ApartmentDetailVo apartmentVo)
    {
        Apartment apartment = apartmentVo.getApartment();

        int rows = apartmentMapper.insertApartment(apartment);

        Long aId = apartment.getId();
        log.info("[insert]  apartment.id={}  [result]]={}",aId,rows);
//        修改stuff关联表
        apartmentVo.getStuffList().forEach(item -> {
            ApartmentStuff apartmentStuff = ApartmentStuff.builder().apartmentId(aId).stuffId(item.getId()).isDelete(0L).build();
            int stuff = apartmentStuffMapper.insertApartmentStuff(apartmentStuff);
            log.info("[insert]  aId:{} --- stuffId: {}  [result]]={}",aId,item.getId(),stuff);
        });
//        修改forbid关联表
        apartmentVo.getForbidList().forEach(item -> {
            ApartmentForbid selector = ApartmentForbid.builder().apartmentId(aId).forbidId(item.getId()).isDelete(0L).build();
            int result = apartmentForbidMapper.insertApartmentForbid(selector);
            log.info("[insert]  aId:{} --- forbidId: {}  [result]]={}",aId,item.getId(),result);
        });
//        修改security关联表
        apartmentVo.getSecurityList().forEach(item -> {
            ApartmentSecurity selector = ApartmentSecurity.builder().apartmentId(aId).securityId(item.getId()).isDelete(0L).build();
            int result = apartmentSecurityMapper.insertApartmentSecurity(selector);
            log.info("[insert]  aId:{} --- securityId: {}  [result]]={}",aId,item.getId(),result);

        });
//        修改feetype关联表
        apartmentVo.getFeetypeList().forEach(item -> {
            ApartmentFeetype selector = ApartmentFeetype.builder().apartmentId(aId).feetypeId(item.getId()).isDelete(0L).build();
            int result = apartmentFeetypeMapper.insertApartmentFeetype(selector);
            log.info("[insert]  aId:{} --- feetypeId: {}  [result]]={}",aId,item.getId(),result);
        });
//        修改image关联表
        apartmentVo.getImageList().forEach(item->{
//            插入file
            File file = File.builder().filename(item).isDelete(0L).build();
            fileMapper.insertFile(file);
//            根据得到的file插入关联表
            ApartmentImage apartmentImage = ApartmentImage.builder().apartmentId(aId).imageId(file.getId()).isDelete(0L).build();
            int result = apartmentImageMapper.insertApartmentImage(apartmentImage);
            log.info("[insert]  aId:{} --- fileId: {}  [result]]={}",aId,file.getId(),result);

        });
//        公寓-学校
        List<ApartmentSchoolVo> schoolList = apartmentVo.getSchoolList();
        schoolList.forEach(i->{
            SchoolApartmentDist apartmentSchool = i.getApartmentSchool();
            apartmentSchool.setApartmentId(aId);
            schoolApartmentDistMapper.insertSchoolApartmentDist(apartmentSchool);
        });
//        公寓-城市-国家
        List<City> city = apartmentVo.getCityList();
        city.forEach(i->{
            ApartmentCountryCity apartmentCityCountry = ApartmentCountryCity.builder()
                    .apartmentId(aId)
                    .cityId(i.getId())
                    .countryId(i.getCountryId())
                    .isDelete(0).build();
            apartmentCountryCityMapper.insert(apartmentCityCountry);
        });

//        TODO 修改房间暂时不做
        return 1;
    }

    /**
     * 修改公寓
     * 
     * @param apartmentVo 公寓
     * @return 结果
     */
    @Transactional
    @Override
    public int updateApartment(ApartmentDetailVo apartmentVo)
    {
        Apartment apartment = apartmentVo.getApartment();
        int apartmentRow = apartmentMapper.updateApartment(apartment);
//        修改stuff关联表
        List<Stuff> stuffList = apartmentVo.getStuffList();

//        apartmentStuffService.update

//        修改forbid关联表

//        修改security关联表

//        修改feetype关联表

//        修改image关联表

//        TODO 修改房间暂时不做
        return 1;
    }

    /**
     * 批量删除公寓
     * 
     * @param ids 需要删除的公寓主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteApartmentByIds(Long[] ids)
    {
        apartmentMapper.deleteCancelByIds(ids);
        return apartmentMapper.deleteApartmentByIds(ids);
    }

    /**
     * 删除公寓信息
     * 
     * @param id 公寓主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteApartmentById(Long id)
    {
        apartmentMapper.deleteCancelById(id);
        return apartmentMapper.deleteApartmentById(id);
    }


}
